package chapter6;

import java.util.LinkedList;

//LC 150
public class EvaluateReversePolishNotation {


    public int evalRPN(String[] tokens) {
        LinkedList<Integer> stack = new LinkedList<>();
        for (int i = 0; i < tokens.length; i++) {
            String s = tokens[i];
            if (!isOpt(s)) {
                stack.push(Integer.parseInt(s));
            }else {
                Integer num2 = stack.pop();
                Integer num1 = stack.pop();
                stack.push(operate(s, num1, num2));
            }
        }
        return stack.pop();
    }

    private Integer operate(String s, Integer num1, Integer num2) {
        if (s.equals("+")){
            return  num1 + num2;
        }else if(s.equals("-")){
            return  num1 - num2;
        }else if(s.equals("*")){
            return  num1 * num2;
        }else if(s.equals("/")){
            return  num1 / num2;
        }
        throw new IllegalArgumentException();
    }

    private boolean isOpt(String s) {
        return "+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s);
    }

}
